package com.example.mqtt.client;

import com.example.mqtt.config.MqttProperties;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 接收消息客户端的方法
 * 订阅主题的client和发送消息的client，可以是同一个client
 */
@Slf4j
@Component
public class MqttSubClient {
    @Autowired
    private MqttClient subMqttClient;
    @Autowired
    private MqttProperties mqttProperties;

    /**
     * 订阅主题
     */
    public void subscribe() {
        subscribe(mqttProperties.getDefaultTopic(), 0);
    }

    /**
     * 订阅某个主题，qos默认为0
     *
     * @param topic 主题名
     */
    public void subscribe(String topic) {
        subscribe(topic, 0);
    }

    /**
     * 订阅某个主题
     *
     * @param topic 主题名
     * @param qos
     */
    public void subscribe(String topic, int qos) {
        try {
            subMqttClient.subscribe(topic, qos);
            log.info("订阅主题:{}",topic);
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 取消订阅某个主题
     *
     * @param topic
     */
    public void unsubscribe(String topic) {
        try {
            subMqttClient.unsubscribe(topic);
            log.info("取消订阅主题:{}",topic);
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 重新连接
     */ 
    public void reConnection() {
        try {
            subMqttClient.connect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     *
     * @param mqttClient
     */
    public static void disconnect(MqttClient mqttClient) {
        try {
            if (mqttClient != null) mqttClient.disconnect();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }

    /**
     * 释放资源
     *
     * @param mqttClient
     */
    public static void close(MqttClient mqttClient) {
        try {
            if (mqttClient != null) mqttClient.close();
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
}
